package hhpoll.dao.hibernate;

import java.util.Date;
import java.util.List;

import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

import hhpoll.dao.PollDAO;
import hhpoll.domain.Poll;

public class HibernatePollDAO extends GenericHibernateDAO<Poll, Long> implements PollDAO {

    public HibernatePollDAO(SessionFactory sessionFactory) {
        super(sessionFactory);
    }

	@Override
	@SuppressWarnings("unchecked")
	public List<Poll> findByAdministrator(String email) {
		return (List<Poll>)this.sessionFactory.getCurrentSession()
		                       .createQuery("from Poll poll where poll.administrator.email = :email")
		                       .setString("email", email)
		                       .list();
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Poll> findByParticipant(String email) {
		return (List<Poll>)this.sessionFactory.getCurrentSession()
		                       .createQuery("select p from Poll as p left outer join p.participants as part where part.email = :email")
		                       .setString("email", email)
		                       .list();
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public List<Poll> listPublic() {
		return (List<Poll>)this.sessionFactory.getCurrentSession()
		                       .createCriteria(Poll.class)
		                       .add(Restrictions.eq("publc", Boolean.TRUE))
		                       .list();
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Poll> findActiveByAdministrator(Date start, Date end, String email) {
		return (List<Poll>)this.sessionFactory.getCurrentSession()
		                       .createCriteria(Poll.class)
		                       .add(Restrictions.ge("startDate", start))
		                       .add(Restrictions.lt("endDate", end))
		                       .createCriteria("administrator")
		                       .add(Restrictions.eq("email", email))
		                       .list();
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Poll> findActiveByParticipant(Date start, Date end, String email) {
		return (List<Poll>)this.sessionFactory.getCurrentSession()
		                       .createCriteria(Poll.class)
		                       .add(Restrictions.ge("startDate", start))
		                       .add(Restrictions.lt("endDate", end))
		                       .createCriteria("participants")
		                       .add(Restrictions.eq("email", email))
		                       .list();
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Poll> listActivePublic(Date start, Date end) {
		return (List<Poll>)this.sessionFactory.getCurrentSession()
		                       .createCriteria(Poll.class)
		                       .add(Restrictions.ge("startDate", start))
		                       .add(Restrictions.lt("endDate", end))
		                       .add(Restrictions.eq("public", Boolean.TRUE))
		                       .list();
	}

}
